import React, { useEffect, useState } from "react";
import { View, Swiper, SwiperItem, Text, Image } from "@tarojs/components";
import Taro, { usePullDownRefresh } from "@tarojs/taro";
import { setData } from "@/src/globalData";
import SubTitle from "@/components/SubTitle";
import Advertisement from "@/components/Advertisement";
import ItemCard from "@/components/ItemCard";
import SearchWrapper from "@/components/SearchWrapper";
import customNavigate from "@/common/hooks/useNavigate";
import zsbIcon from "@/images/icon_zsb.png";
import gqzIcon from "@/images/icon_gqz.png";
import kyIcon from "@/images/icon_ky.png";
import zgzIcon from "@/images/icon_zgz.png";
import placeholderImg from "@/images/placeholder.png";

import * as api from "./api";
import { SchoolItem, MajorItem } from "./data";
import "./index.scss";

const Index: React.FC<{}> = () => {
  const [schoolData, setSchoolData] = useState<SchoolItem[][]>([]);
  const [majorData, setMajorData] = useState<MajorItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshAdFlag,setRefreshAdFlag] = useState(false)

  const goSchoolList = () => {
    customNavigate("/pages/schoolList/index");
  };

  const goMajorList = () => {
    customNavigate("/pages/majorList/index");
  };

  const goGoodsList = (category) => {
    setData("goodsTitle", "");
    Taro.navigateTo({
      url: `/pages/goods/index?category=${category}`,
    });
  };

  const getSchoolData = async () => {
    try {
      let search_info: any = {}
      if (Taro.getStorageSync("city")) {
        search_info.city = Taro.getStorageSync("city")[1];
        search_info.province = Taro.getStorageSync("city")[0];
      }
      const { result, status } = await api.university_school_hotsearch({
        search_info: JSON.stringify(search_info),
      });
      if (status === "ok") {
        const sourceData: SchoolItem[] = result.data_list;
        const arr: SchoolItem[][] = [];
        for (let i in sourceData) {
          if (Number(i) === 0 || Number(i) % 4 === 0) {
            arr.push([sourceData[i]]);
          } else {
            arr[arr.length - 1].push(sourceData[i]);
          }
        }
        setSchoolData(arr);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      setLoading(false);
      Taro.stopPullDownRefresh();
    }
  };

  const getMajorData = async () => {
    try {
      const { result, status } = await api.university_major_hotsearch({
        search_info: JSON.stringify({}),
      });
      status === "ok" && setMajorData(result.data_list);
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      setLoading(false);
      Taro.stopPullDownRefresh();
    }
  };

  useEffect(() => {
    getSchoolData();
    getMajorData();
  }, []);

  usePullDownRefresh(() => {
    getSchoolData();
    getMajorData();
    setRefreshAdFlag(!refreshAdFlag)
  });

  return (
    <View className="index">
      <SearchWrapper
        isShowScan={true}
        onSearch={(value) => {
          setData("goodsTitle", value);
          Taro.navigateTo({
            url: `/pages/goods/index?title=${value}`,
          });
        }}
        onSelectRegion={() => {
          getSchoolData();
        }}
      />

      <Advertisement className="banner" label="index_banner" interval={5000} refreshAdFlag={refreshAdFlag}/>

      <View className="cate">
        <View className="item" onClick={() => goGoodsList("undergraduate")}>
          <Image className="icon" src={zsbIcon} />
          <View className="text">专升本</View>
        </View>
        <View className="item" onClick={() => goGoodsList("specialty")}>
          <Image className="icon" src={gqzIcon} />
          <View className="text">高起专</View>
        </View>
        <View className="item" onClick={() => goGoodsList("graduate")}>
          <Image className="icon" src={kyIcon} />
          <View className="text">考研</View>
        </View>
        <View className="item" onClick={() => goGoodsList("highcost")}>
          <Image className="icon" src={zgzIcon} />
          <View className="text">高起本</View>
        </View>
      </View>

      <Advertisement className="ad-space" label="index_mid" interval={7000} refreshAdFlag={refreshAdFlag}/>

      <SubTitle
        title={"热门学校"}
        rightCon={
          <Text onClick={goSchoolList} className={"more"}>
            查看更多 {'>'}
          </Text>
        }
      />

      {schoolData.length ? (
        <Swiper
          className="school-wrapper"
          indicatorDots={false}
        >
          {schoolData.map((item, index) => {
            return (
              <SwiperItem key={JSON.stringify(item)}>
                <View className="school-card">
                  {item.map((it) => (
                    <View
                      className="school-item"
                      key={it.id}
                      onClick={() => {
                        Taro.navigateTo({
                          url: `/pages/schoolDetail/index?school_id=${it.id}`,
                        });
                      }}
                    >
                      <Image className="school-logo" src={it.icons} />
                      <View className="school-con">
                        <View className="name">{it.name}</View>
                        <View className="desc">{it.content}</View>
                      </View>
                    </View>
                  ))}
                </View>
              </SwiperItem>
            );
          })}
        </Swiper>
      ) : (
        <View className="no-data-placeholder">
        <Image src={placeholderImg} className="placeholder-img" />
        <View className="no-data">暂无数据</View>
      </View>
      )}


      <SubTitle
        title={"热门专业"}
        rightCon={
          <Text onClick={goMajorList} className={"more"}>
            查看更多 >
          </Text>
        }
      />

      <View className="major-wrapper">
        {majorData.map((item) => (
          <ItemCard
            onClick={() => {
              Taro.navigateTo({
                url: `/pages/majorDetail/index?major_id=${item.id}`,
              });
            }}
            key={item.id}
            {...item}
          />
        ))}
      </View>
    </View>
  );
};

export default Index;
